package com.gjx.clock

import android.content.Context
import android.content.Intent
import com.gjx.clock.entity.NormalAlarmClock
import com.gjx.clock.entity.RestAlarmClock
import com.gjx.clock.service.ForwardService
import java.util.*

object AlarmHelper {
    fun setAlarm(context: Context,clock: NormalAlarmClock,notify: Boolean =true) {
        val now = Calendar.getInstance()
        val alarmTime = Calendar.getInstance()
        alarmTime.set(Calendar.HOUR_OF_DAY, clock.hour)
        alarmTime.set(Calendar.MINUTE, clock.minute)
        alarmTime.set(Calendar.SECOND, 0)

        if (alarmTime.before(now)) {
            alarmTime.add(Calendar.DATE, 1)
        }
        val newAlarm = Intent(ForwardService.ACTION_ADD_ONE_ALARM)
        val timeInMillis = alarmTime.timeInMillis
        newAlarm.putExtra("triggerAtMillis", timeInMillis)
        newAlarm.putExtra("requestCode", clock.id)
        newAlarm.putExtra("notify", notify)

        newAlarm.setPackage(context.packageName)
        context.sendBroadcast(newAlarm)
    }

    fun setRestAlarm(context: Context,delayTime: Int,notify: Boolean =true,action:String){
        val alarmTime = Calendar.getInstance()
        alarmTime.set(Calendar.SECOND,0)
        alarmTime.add(Calendar.MINUTE, delayTime)

        val newAlarm = Intent(ForwardService.ACTION_ADD_ONE_ALARM)
        val timeInMillis = alarmTime.timeInMillis
        newAlarm.putExtra("triggerAtMillis", timeInMillis)
        newAlarm.putExtra("requestCode", ClockApplication.restId.toLong())
        newAlarm.putExtra("notify", notify)
        newAlarm.putExtra("restAction", action)

        newAlarm.setPackage(context.packageName)
        context.sendBroadcast(newAlarm)
    }

    fun cancelAlarm(context: Context,clock: NormalAlarmClock,notify: Boolean =false) {
        val cancelIntent = Intent(ForwardService.ACTION_CANCEL_ONE_ALARM)
        cancelIntent.putExtra("requestCode", clock.id)
        cancelIntent.putExtra("notify", notify)
        cancelIntent.setPackage(context.packageName)
        context.sendBroadcast(cancelIntent)
    }
    fun cancelRestAlarm(context: Context,notify: Boolean =false) {
        val cancelIntent = Intent(ForwardService.ACTION_CANCEL_ONE_ALARM)
        cancelIntent.putExtra("requestCode", ClockApplication.restId)
        cancelIntent.putExtra("notify", notify)
        cancelIntent.setPackage(context.packageName)
        context.sendBroadcast(cancelIntent)
    }

}
